from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from user.models import User, VSession, WarZone, Company, IPSystem
from user.dataCheck import DataCheck
from log.models import UserLog
from storehouse.models import Storehouse
import pdb, os, time, requests, base64, json
import datetime
import logging, random
from conf.sysConfig import config
from PIL import Image, ImageDraw, ImageFont
from software.views.view_download import download
from order.views.createOrder import random_str
from software.utils import fileStore
from pprint import pprint

# from io import BytesIO

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
userSystem = config["userSystem"]
isUserSystem = config["isUserSystem"]
redirect_url = config["redirect_url"]
de_redirect_url = config["de_redirect_url"]
user_redirect_url = config["user_redirect_url"]
userPort = config["userPort"]
userToken = config["userToken"]
userInfo = config["userInfo"]
userCode = config["userCode"]

datacheck = DataCheck()


def register(request, *args, **kwargs):
    """
        url    : /user/register/
        method : POST

    :param request:
              username: data.username, // 用户名
              password: data.password  //密码
              userType: data.userType  //用户类型 
              phone: data.phone  //电话
              name: data.name  //姓名              
              warZoneId: data.warZoneId  //所属战区
              companyId: data.companyId  //所属单位          

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data

    warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
    company = Company.objects.get(pk=requestParam['companyId'])

    user = User.objects.create(
        username=requestParam['username'],
        # password=make_password(requestParam['password'],None,'pbkdf2_sha256'),   #自带加密
        password=requestParam['password'],
        phone=requestParam['phone'],
        name=requestParam['name'],
        userType=requestParam['userType'],
        warZone=warZone,
        company=company,
    )

    data = {
        "code": 0,
        "msg": "success",
    }

    return JsonResponse(data)


def login(request, *args, **kwargs):
    """
        url    : /user/login/
        method : POST

    :param request:
               username
               password

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息
              'token'        // token
              'userType'     // 用户类型
    """

    # print(request.session.get("valid_code"))
    # print(request.session.items())
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # 2020.11.17 update access usersystem add user login
    # print(requestParam)
    access_token = ""
    refreshToken = ""
    if isUserSystem:
        if requestParam["isSingleLogin"]:
            access_token = requestParam["accessToken"]
            refreshToken = requestParam["refreshToken"]
        else:
            # code = requests.get(userSystem + ":" + userPort + userToken)
            if requestParam["systemType"] == "1":
                credirect_url = de_redirect_url
            elif requestParam["systemType"] == "2":
                credirect_url = redirect_url
            elif requestParam["systemType"] == "3":
                credirect_url = user_redirect_url
            else:
                pass

            body = {
                "code": requestParam["code"],
                "grant_type": "authorization_code",
                "client_id": config["client_id"],
                "client_secret": config["client_secret"],
                "redirect_uri": credirect_url,
            }

            # body = {
            #      "code": requestParam["code"],
            #      "grant_type": "authorization_code",
            #       # "client_id": config["client_id"],
            #       # "client_secret": config["client_secret"],
            #      "redirect_uri": redirect_url,
            # }
            # data_client = config["client_id"] + ':' + config["client_secret"]
            # # pdb.set_trace()
            # bytes_url = data_client.encode("utf-8")
            # b_url = base64.b64encode(bytes_url)
            # str_url = str(b_url, "utf-8")
            headers = {
                'Content-Type': "application/x-www-form-urlencoded",
                # 'Authorization': 'Basic ' + str_url
            }
            # print(userSystem + ":" + userPort + userToken)
            # print("body:", body)
            # print("headers:", headers)
            # pdb.set_trace()
            try:
                token = requests.post(
                    userSystem + ":" + userPort + userToken,
                    data=body,
                    headers=headers
                )
                logger_request.info(token.text)
            except:
                data = {
                    'code': 0,
                    'msg': 'userSystem error',
                    "token": '',
                    "refreshToken": '',
                    "userType": '',
                    "userName": '',
                    "userIP": '',
                    "isMasterStore": '',
                }
                logger_request.info(data)
                return JsonResponse(data)

            if token.status_code == 200:
                access_token = json.loads(token.text)["access_token"]
                # print(access_token)
                refreshToken = json.loads(token.text)["refresh_token"]
                # pdb.set_trace()
            else:
                data = {
                    'code': 0,
                    'msg': 'userSystem error',
                    "token": '',
                    "userType": '',
                    "userName": '',
                    "userIP": '',
                    "isMasterStore": '',
                }
                logger_request.info(data)
                return JsonResponse(data)

        # get info
        # print(access_token)
        dic = {
            "token": access_token
        }
        userRes = requests.get(userSystem + ":" + userPort + userInfo, params=dic)
        # userData = requests.get("http://" + userSystem + ":" + userPort + "/auth/user/describe", 
        #     headers={
        #         "Authorization": "Bearer " + access_token
        #     }, 
        #     # params=access_token
        # )
        data1 = json.loads(userRes.text)
        userData1 = data1["data"]
        userData = userData1["user_name"]
        # pprint(userData)
        if userData1["active"]:
            user = User.objects.filter(userId=userData["userId"])
            if user.exists():
                user = User.objects.get(userId=userData["userId"])
                user.userToken = access_token
                user.save()
                user.refreshToken = refreshToken
                user.save()
            else:
                user = registerSystem({
                    "userId": userData["userId"],
                    "username": userData["username"],
                    "name": userData["realName"],
                    "phone": userData["phone"],
                    "userType": "3",
                    "warZoneId": "1",
                    "companyId": "1",
                    "position": userData["position"],
                    "nation": userData["nation"],
                    "email": userData["email"],
                    "borthTime": userData["borthTime"],
                    "cardId": userData["cardId"],
                    "sex": userData["sex"],
                    "deptId": userData["deptId"],
                    "postLevel": userData["postLevel"],
                    "politivalStatus": userData["politivalStatus"],
                    "access_token": access_token,
                    "refreshToken": refreshToken
                })
                storehouse = Storehouse.objects.filter(pk=1).first()
                storehouse.user.add(user)
                storehouse.save()
        else:
            data = {
                'code': 1,
                'msg': 'userSystem None',
                "token": '',
                "userType": '',
                "userName": '',
                "userIP": '',
                "isMasterStore": '',
            }
            logger_request.info(data)
            return JsonResponse(data)

        # code user
        try:
            dic = {
                "clientId": config["client_id"]
            }
            headers1 = {
                'Content-Type': "application/x-www-form-urlencoded",
                'Authorization': 'Bearer' + ' ' + access_token
            }
            userCodeRes = requests.post(userSystem + ":" + userPort + userCode,
                                        headers=headers1,
                                        params=dic)
            userCodeRes = json.loads(userCodeRes.text)
            logger_request.info(userCodeRes)
            codeDate = userCodeRes["data"]["roleCode"]
            logger_request.info(codeDate)
            for i in codeDate:
                if i not in ["1", "2", "3", "4"]:
                    data = {
                        'code': 0,
                        'msg': 'userType error',
                        "token": '',
                        "userType": '',
                        "userName": '',
                        "userIP": '',
                        "isMasterStore": '',
                    }
                    logger_request.info(data)
                    return JsonResponse(data)
                if i == "4":
                    user.isSupervisor = True
                else:
                    user.userType = i
            user.save()

        except:
            data = {
                'code': 0,
                'msg': 'userSystem error',
                "token": '',
                "userType": '',
                "userName": '',
                "userIP": '',
                "isMasterStore": '',
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        users = User.objects.filter(username=requestParam['username'])
        if not users.exists():
            data = {
                'code': 0,
                'msg': 'passwordError',
                "token": '',
                "userType": '',
                "userName": '',
                "userIP": '',
                "isMasterStore": '',
            }
            logger_request.info(data)
            return JsonResponse(data)
        user = users[0]
        if user.password != requestParam["password"]:
            data = {
                'code': 0,
                'msg': 'password error',
                "token": '',
                "userType": '',
                "userName": '',
                "userIP": '',
                "isMasterStore": '',
            }
            logger_request.info(data)
            return JsonResponse(data)
    # pdb.set_trace()
    userType = user.userType
    if requestParam['systemType'] == '1' and userType == '1':
        pass
    elif requestParam['systemType'] == '2' and userType == '2':
        pass
    elif requestParam['systemType'] == '3' and userType == '3':
        pass
    else:
        data = {
            'code': 0,
            'msg': 'userType error',
            "token": '',
            "userType": userType,
            "userName": '',
            "userIP": '',
            "isMasterStore": '',
        }
        logger_request.info(data)
        return JsonResponse(data)

        # request.session[]
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')
    # pdb.set_trace()
    userIP = IPSystem.objects.filter(userIP=ip, user=user)
    if userIP.exists():
        userIP1 = userIP[0]
        if userIP1.isForbid == False:
            userIP2 = UserLog.objects.create(
                user=user,
                userIP=ip,
                operate='登录'
            )
        else:
            data = {
                "code": 0,
                "msg": "IP is reject",
                "token": '',
                "userType": '',
                "userName": '',
                "userIP": '',
                "warZone": '',
                "company": '',
                "storehouseName": '',
                "storehouseNameId": '',
                "warZoneId": '',
                "companyId": '',
            }
            logger_request.info(data)
            return JsonResponse(data)
    else:
        userIP2 = UserLog.objects.create(
            user=user,
            userIP=ip,
            operate='登录'
        )
        userIP3 = IPSystem.objects.create(
            user=user,
            userIP=ip,
        )
    # add session

    if isUserSystem:
        token = access_token
    else:
        token = datacheck.getLocalToken()

    vsessions = VSession.objects.filter(user=user)
    if vsessions.exists():
        vsession = vsessions[0]
        vsession.token = token
        vsession.save()
        vsession.isActive = 1
        vsession.save()
    else:
        vsession = VSession.objects.create(
            token=token,
            user=user,
        )
    if userType == '2':
        storehouse = Storehouse.objects.filter(user=user).first()
        data = {
            "code": 0,
            "msg": "success",
            "token": vsession.token,
            "refreshToken": user.refreshToken,
            "userType": user.userType,
            "userName": user.username,
            "userIP": ip,
            "isMasterStore": storehouse.storeIPType,
            "isSuper": user.isSupervisor
        }
        logger_request.info(data)
        return JsonResponse(data)
    elif userType == '1':
        storehouse = Storehouse.objects.filter(user=user).first()
        data = {
            "code": 0,
            "msg": "success",
            "token": vsession.token,
            "refreshToken": user.refreshToken,
            "userType": user.userType,
            "userName": user.username,
            "userIP": ip,
            "warZone": user.warZone.name,
            "company": user.company.name,
            "storehouseName": storehouse.storehouseName,
            "storehouseNameId": storehouse.id,
            "warZoneId": user.warZone.id,
            "companyId": user.company.id,
            "isSuper": user.isSupervisor
        }
        logger_request.info(data)
        return JsonResponse(data)
    else:
        data = {
            "code": 0,
            "msg": "success",
            "token": vsession.token,
            "refreshToken": user.refreshToken,
            "userType": user.userType,
            "userName": user.username,
            "userIP": ip,
            "warZone": '',
            "company": '',
            "storehouseName": '',
            "storehouseNameId": '',
            "warZoneId": '',
            "companyId": '',
            "isSuper": user.isSupervisor
        }
        logger_request.info(data)
        return JsonResponse(data)


def logout(request, *args, **kwargs):
    """
        url    : /user/logout/
        method : POST

    :param request:
               token          // 秘钥

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # 验证token
    # code = requests.get(userSystem + ":" + userPort + userToken)
    if isUserSystem:
        body = {
            "remoteIp": config['remoteIp']
        }
        # str_url = base64.b64encode(requestParam['token'])
        headers = {'content-type': "application/x-www-from-urlencoded",
                   'Authorization': 'Bearer ' + requestParam['token']}
        token = requests.post(userSystem + ":" + userPort + config["userOut"], data=body, headers=headers)
    # access_token = token.content
    # refreshToken = token.content

    vsession = VSession.objects.filter(token=requestParam['token'])
    vs = vsession[0]
    vs.delete()
    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


# 获取验证码图片的视图
def get_valid_img(request):
    form = request.checkForm
    requestParam = form.cleaned_data

    # 获取随机颜色的函数
    # def get_random_color():
    #     return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    # 生成一个图片对象
    img_obj = Image.new(
        'RGB',
        (220, 50),
        (255, 255, 255)
        # get_random_color()
    )
    # 在生成的图片上写字符
    # 生成一个图片画笔对象
    draw_obj = ImageDraw.Draw(img_obj)
    # 加载字体文件， 得到一个字体对象
    font_obj = ImageFont.truetype(os.path.join(tmpDir, 'Lanehum.ttf'), 28)
    # 开始生成随机字符串并且写到图片上
    tmp_list = []
    for i in range(4):
        # u = chr(random.randint(65, 90))  # 生成大写字母
        # l = chr(random.randint(97, 122))  # 生成小写字母
        n = str(random.randint(0, 9))  # 生成数字，注意要转换成字符串类型
        tmp = random.choice([n])
        tmp_list.append(tmp)
        ls3 = ''.join(tmp_list)  # 拼接列表字符串
        # draw_obj.text((20 + 40 * i, 0), tmp, fill=get_random_color(), font=font_obj)
        draw_obj.text((20 + 40 * i, 0), tmp, fill=(0, 0, 0), font=font_obj)
    # print(tmp_list)
    # 保存到session
    request.session["valid_code"] = "".join(tmp_list)
    # print(request.session.items())
    # 加干扰线
    width = 220  # 图片宽度（防止越界）
    height = 50
    for i in range(3):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        # draw_obj.line((x1, y1, x2, y2), fill=get_random_color())
        draw_obj.line((x1, y1, x2, y2))

    # 加干扰点
    for i in range(30):
        # draw_obj.point((random.randint(0, width), random.randint(0, height)), fill=get_random_color())
        draw_obj.point((random.randint(0, width), random.randint(0, height)))
        x = random.randint(0, width)
        y = random.randint(0, height)
        # draw_obj.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
        draw_obj.arc((x, y, x + 4, y + 4), 0, 90)

    # 不需要在硬盘上保存文件，直接在内存中加载就可以
    # io_obj = BytesIO()
    # 将生成的图片数据保存在io对象中
    name = random_str(32) + ".png"
    img_obj.save(os.path.join(tmpDir, name))

    # 从io对象里面取上一步保存的数据
    # data = io_obj.getvalue()
    data = {
        'msg': 'success',
        'code': 0,
        'imageUrl': download(name, 'tmpFile', os.path.join(tmpDir, name))[1],
        'codeStr': ls3,
    }
    return JsonResponse(data)


def isOnline(request, *args, **kwargs):
    """
        url    : /user/isOnline/
        method : POST

    :param request:
               token          // 秘钥

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    # 验证token

    vsession = VSession.objects.filter(token=requestParam['token']).first()
    nowTime = datetime.datetime.now()
    vsession.lastVisiteTime = nowTime
    # pdb.set_trace()

    nowdateStamp = time.mktime(nowTime.timetuple())
    createtimeStamp = time.mktime(vsession.createTime.timetuple())
    duration = round((nowdateStamp - createtimeStamp) / 60)

    # print(vsession.duration)
    vsession.duration = duration
    vsession.save()
    ip = datacheck.getIP(request)
    user = datacheck.getUser(requestParam['token'])
    userItem = IPSystem.objects.filter(userIP=ip, user=user).first()
    userItem.duration = duration
    userItem.save()

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def registerSystem(requestParam):
    warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
    company = Company.objects.get(pk=requestParam['companyId'])
    # pdb.set_trace()
    user = User.objects.create(
        userId=requestParam['userId'],
        username=requestParam['username'],
        name=requestParam['name'],
        phone=requestParam['phone'],
        position=requestParam['position'],
        nation=requestParam['nation'],
        email=requestParam['email'],
        borthTime=requestParam['borthTime'],
        cardId=requestParam['cardId'],
        sex=requestParam['sex'],
        deptId=requestParam['deptId'],
        politivalStatus=requestParam['politivalStatus'],
        postLevel=requestParam['postLevel'],
        # password=make_password(requestParam['password'],None,'pbkdf2_sha256'),   #自带加密
        # password=requestParam['password'],
        userType=requestParam['userType'],
        warZone=warZone,
        company=company,
        refreshToken=requestParam['refreshToken'],
        userToken=requestParam['access_token']
    )
    return user


def isUserSystemWeb(request, *args, **kwargs):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')
    data = {
        "code": 0,
        "msg": "success",
        "isUserSystem": isUserSystem,
        "ip": ip
    }
    logger_request.info(data)
    return JsonResponse(data)


def getIp():
    pass


def updateToken(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    # old user
    vsessions = VSession.objects.filter(token=requestParam['token'])
    vsession = vsessions[0]

    dic = {
        "token": requestParam["newToken"]
    }
    userRes = requests.get(userSystem + ":" + userPort + userInfo, params=dic)
    data1 = json.loads(userRes.text)
    userData1 = data1["data"]
    userData = userData1["user_name"]
    if userData1["active"]:
        # newToken user
        user = User.objects.filter(userId=userData["userId"])
        if not user.exists() or user[0].id != vsession.user.id:
            data = {
                "code": 1,
                "msg": "error",
                "token": vsession.token,
            }
            logger_request.info(data)
            return JsonResponse(data)
        vsession.token = requestParam["newToken"]
        vsession.save()
        data = {
            "code": 0,
            "msg": "success",
            "token": vsession.token,
        }
        logger_request.info(data)
        return JsonResponse(data)
    else:
        data = {
            "code": 0,
            "msg": "success",
            "token": vsession.token,
        }
        logger_request.info(data)
        return JsonResponse(data)
